<?php

namespace apiend\modules\user\models;

use common\models\user\UserFollow;

/**
 * 用户关注模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class FollowForm extends \common\base\Model {

    use \common\traits\Constants;

    /**
     * @name $model 模型标识
     * @var integer teacher|school
     */
    public $model;

    /**
     * @name $model_id 模型ID
     * @var integer 1
     */
    public $model_id;

    /**
     * @name $user_id 用户ID
     * @var integer 1
     */
    public $user_id;

    public function rules() {
        return [
            ['model', 'in', 'range' => [UserFollow::MODEL_SCHOOL, UserFollow::MODEL_TEACHER]],
            [['model', 'model_id', 'user_id'], 'required'],
            [['model_id', 'user_id'], 'integer'],
            [['model_id'], 'validateFollowModel'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'model' => '关注内容',
            'user_id' => '用户ID',
            'model_id' => '被关注内容ID',
        ];
    }

    public function validateFollowModel($attribute) {
        if (!$this->hasErrors()) {
            $modelClass = $this->getArModel($this->model);
            if ($modelClass !== false) {
                $model = $modelClass::findOne($this->$attribute);
                if (!$model) {
                    $this->addError($attribute, '关注内容不存在');
                }
            } else {
                $this->addError($attribute, '关注的内容不存在');
            }
        }
    }

    protected function getArModel($model) {
        $aralias = [
            UserFollow::MODEL_TEACHER => '\common\models\teacher\Teacher',
            UserFollow::MODEL_SCHOOL => '\common\models\school\School',
        ];
        return isset($aralias[$model]) ? $aralias[$model] : false;
    }

    /**
     * 关注/取消关注
     * @param array $params
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            $this->dumpError('关注失败', $this->errors);
        }

        $model = UserFollow::findOrNew($this->attributes);

        if ($model->isNewRecord) {
            if (!$model->save()) {
                $this->dumpError('关注失败', $model->errors);
            }
            return true;
        }

        return !$model->delete();
    }

}
